# coding:utf-8
# writingtime: 2022-8-13

import time
import os
import pandas as pd
import random as rm
import numpy as np
from math import log10
from scoreFunction import f, getScore
import matplotlib.pyplot as plt
import time


class Analyze():
    def __init__(self, scorefunc, q):
        """

        :param scorefunc:
        :param q:
        """
        self.func = scorefunc
        self.q = q

    def makedir(self, dirnames):
        """
        function: 创建文件夹
        :param dirnames: 文件夹名
        :return:
        """
        try:
            os.makedirs(dirnames)
        except:
            print("folder already exists")


    def case2(self):
        """

        :return:
        """

        for i in range(40):
            filename = r'data/case2/' + str(i + 1) + '.csv'
            # data = pd.read_csv(filename, names=["ul", "ur", "vl", "vr"], encoding='utf-8')
            data = pd.read_csv(filename, encoding='utf-8')
            # print(data.shape)
            if data.shape[1] == 5:
                continue
            else:
                data = pd.read_csv(filename, names=["ul", "ur", "vl", "vr"], encoding='utf-8')
                # data['score'] = getScore(data['ul'], data['ur'], data['vl'], data['vr'])
                # print(filename)
                te = []
                for i in range(data.shape[0]):
                    te.append(self.func(data['ul'][i], data['ur'][i], data['vl'][i], data['vr'][i]))
                data['score'] = te
                # print(data['score'])
                # break
                pd.DataFrame(data).to_csv(filename, index=False, header=False)
                print(filename, 'get score')
        temp = pd.read_csv(r'data/case2/1.csv', names=["ul", "ur", "vl", "vr", 'score'])
        for i in range(1, 40):
            filename = r'data/case2/' + str(i + 1) + '.csv'
            data = pd.read_csv(filename, names=["ul", "ur", "vl", "vr", 'score'])
            temp = pd.concat([temp, data], ignore_index=True)
            print(filename, 'concat')
        print('连接后形状为：', temp.shape)
        a = temp['score'].value_counts()
        a = a.rename_axis('score').reset_index(name='counts')

        # arr=list(map(lambda x,y : [x,y], list(a['score']), list(a['counts'])))
        # arr.sort(key=lambda x:x[0],reverse=False)
        # ar2 = [[row[i] for row in arr] for i in range(len(arr[0]))]
        # # print(ar2)
        # plt.scatter(ar2[0],ar2[1])
        # plt.hist(ar2[1], bins=12, rwidth=0.9, density=True)
        # print(temp['score'][0])
        # new=pd.DataFrame(ddd)
        print('\n得分统计结果\n', a, '\n')
        if 1:
            merge_data = pd.merge(temp, a)
            print('与得分链接后的dataFrame\n', merge_data)
            merge_data.to_csv(r'result/case2.csv', index=False, header=False)
            print(merge_data[merge_data['counts'] > 1], '\n')
            print('保留6位小数时，通过测试的IVq-ROFS的数量为：', merge_data[merge_data['counts'] == 1].__len__())
            # print('有{}组数据相等'.format(a.shape[0]))
        # print(data['score'].value_counts())
        plt.show()

    @staticmethod
    def case1_i_updata():
        """
        符合直觉模糊集的数据
        :return:
        """
        # 保留的小数为
        round_numb = 8
        star_time = time.time()
        data = pd.read_csv(r'data/case1/' + str(1) + '.csv', names=["ul", "ur", "vl", "vr"])
        # 筛选区间值直觉模糊数获取行索引
        # new_data = data[(data['ul'] <= data['ur']) & (data['vl'] <= data['vr']) & (data['vl'] + data['vr'] <= 1)]
        index = data.index.tolist()
        # 根据行标索引结果
        result = pd.read_csv(r'result/case1/' + str(1) + '.csv', names=["score"]).loc[index]
        # 将得分与原始数据合并
        all_data=pd.concat([data,result],axis=1, ignore_index=True)
        print('result/case1/' + str(1) + '.csv', 'is read')
        for i in range(2, 66):
            data = pd.read_csv(r'data/case1/' + str(i) + '.csv', names=["ul", "ur", "vl", "vr"])
            # new_data = data[(data['ul'] <= data['ur']) & (data['vl'] <= data['vr']) & (data['vl'] + data['vr'] <= 1)]
            index = data.index.tolist()
            result=pd.read_csv(r'result/case1/' + str(i) + '.csv', names=["score"]).loc[index]
            tt=pd.concat([data,result],axis=1, ignore_index=True)
            all_data=pd.concat([all_data,tt],axis=0,ignore_index=True)

            print('result/case1/' + str(i) + '.csv', 'is read')

        # print(all_data)
        all_data.columns=["ul", "ur", "vl", "vr","score"]
        temp = all_data['score'].value_counts().rename_axis('score').reset_index(name='counts')
        final_result=pd.merge(all_data,temp)

        # print(final_result.sort_values(by='counts',ascending=False))
        print('\n****************得分相同的情况如下****************\n',final_result[final_result['counts'] > 1])
        final_result[final_result['counts'] > 1].to_csv('result/sameValue.csv',index=False)
        print('****************得分通过的情况如下****************\n',final_result[final_result['counts'] == 1])
        print('**********************************************************')
        print('case1的区间值模糊数保留2位小数，其中符合区间值直觉模糊环境数有%s个，' % str(final_result.__len__()), '保留%s小数时，' % str(round_numb),
              '通过得分函数测试的数据有%s个，' % str(temp[temp['counts'] == 1].__len__()), '通过率为：',
              final_result[final_result['counts'] == 1].__len__() / final_result.__len__())
        print('总耗时：', (time.time() - star_time), 's')

if __name__ == "__main__":
    # 统计1亿个数据
    # Analyze.case1()
    # 检索符合区间值直觉模糊集的数据
    Analyze.case1_i_updata()
